'use strict';

const jsYaml = require('js-yaml'),
    fs = require('fs'),
    lodash = require('lodash.merge'),
    path = require('path');

class Helper {
    constructor() {
        this.filesPathList = [];
    }
    // 获取项目名
    getProjectName() {
        const list = process.cwd().split(path.sep);
        const projectName = list[list.length - 1];
        return projectName;
    }

    // 根据输入参数获取path
    getPathByParam(param) {
        const val = param.replace(this.getProjectName(), '');
        let filePath = path.normalize(val);
        filePath = path.join(process.cwd(), filePath);
        return filePath;
    }

    // 获取文件夹下的文件path列表
    getFilesPathByDir(directory) {
        const files = fs.readdirSync(directory);
        for (const file of files) {
            const p = path.join(directory, file);
            const stat = fs.statSync(p);
            if (stat.isDirectory()) {
                // 如果是目录
                this.getFilesPathByDir(p);
            } else if (stat.isFile()) {
                this.filesPathList.push(p);
            }
        }
        return this.filesPathList;
    }

    // 获取yaml path
    getYamlFilesPath(list) {
        return list.filter(el => {
            return path.extname(el) === '.yaml';
        });
    }

    // 合并
    merge(filesArray) {
        let mergedConfig;
        filesArray.forEach(file => {
            const parsedConfig = jsYaml.safeLoad(fs.readFileSync(file, 'utf8'));
            if (!mergedConfig) {
                mergedConfig = parsedConfig;
            } else {
                lodash(mergedConfig, parsedConfig);
            }
        });
        return mergedConfig;
    }
}
module.exports = Helper;